/**
 * Copyright (c) 2010 S9,Inc.All rights reserved.
 * Created by 2013-6-5 
 */
package cn.jdy.framework.db.mongodb;

import java.net.UnknownHostException;

import com.mongodb.DB;
import com.mongodb.Mongo;
import com.mongodb.MongoOptions;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.util.PropertyUtil;

/**
 * mongoDB 初始化及获取数据库 mongoDB 初始化及获取数据库
 * 
 * @author: wuzhiliang
 * @data: 2013-6-27
 */
public class MongoDBInit {

  private static String ip;// IP
  private static int port;// 端口号
  private static int poolSize;// 连接池大小
  private static String dbName;// 数据库名
  private static String dbUserName;// 数据库用户名
  private static String dbPassWord;// 数据库密码
  private static Mongo mongo;

  /**** mongodb 对应配置文件里的key ***/
  public static final String CONFIG = "config"; // 配置文件名
  public static final String MONGO_IP = "mongoDB.ip";// IP
  public static final String MONGO_PORT = "mongoDB.port";// 端口号
  public static final String MONGO_POOLSIZE = "mongoDB.poolSize";// 连接池大小
  public static final String MONGO_DBNAME = "mongoDB.dbName";// 数据库名
  public static final String MONGO_DBUSERNAME = "mongoDB.dbUserName";// 数据库用户名
  public static final String MONGO_DBPASSWORD = "mongoDB.dbPassWord";// 数据库密码

  public static DB db;// 数据库连接

  private MongoDBInit() {

  }

  /**
   * 获取数据库连接
   * 
   * @return
   * @throws Exception
   */
  public static DB getDB() {
    try {
      if (null == mongo) {
        init();
      }
      db = mongo.getDB(dbName);
      /* 用户认证 */
      boolean flag = db.authenticate(dbUserName, dbPassWord.toCharArray());
      if (flag) {
        return db;
      } else {
        throw new BaseException("mongoDB数据库认证失败！");
      }
    } catch (Exception e) {
      throw new BaseException("获取DB失败", e);
    }
  }

  /**
   * 初始化mongoDB 数据库连接池
   * 
   * @return
   * @throws Exception
   */
  public static void init() throws Exception {

    ip = PropertyUtil.getProInfo(CONFIG, MONGO_IP);
    port = Integer.valueOf(PropertyUtil.getProInfo(CONFIG, MONGO_PORT));
    poolSize = Integer.valueOf(PropertyUtil.getProInfo(CONFIG, MONGO_POOLSIZE));
    dbName = PropertyUtil.getProInfo(CONFIG, MONGO_DBNAME);
    dbUserName = PropertyUtil.getProInfo(CONFIG, MONGO_DBUSERNAME);
    dbPassWord = PropertyUtil.getProInfo(CONFIG, MONGO_DBPASSWORD);

    try {
      mongo = new Mongo(ip, port);
      /* 设置 数据库连接 池 */
      MongoOptions mgOpt = mongo.getMongoOptions(); // 参数
      mgOpt.autoConnectRetry = false; // 连接发生错误是否重连 默认false
      mgOpt.connectionsPerHost = poolSize;// 每个主机的连接池大小 默认10
    } catch (UnknownHostException e) {
      throw new Exception("初始化mongoDB失败", e);
    }

  }

}
